import * as vscode from 'vscode';
import * as fs from 'fs';
import * as path from 'path';
import * as child_process from 'child_process';
import { AuthService } from './authService';

export interface ProjectInfo {
  branch: string;
  timestamp: string;
  operator: string;
  projectName: string;
  workspacePath: string;
  summary?: {
    projectDescription?: string;
    erEntities?: any[];
    codeAnalysis?: any;
  };
}

export class ProjectInfoService {
  private context: vscode.ExtensionContext;
  private authService: AuthService;
  private infoDir: string;
  private updateTimer: NodeJS.Timeout | undefined;

  constructor(context: vscode.ExtensionContext, authService: AuthService) {
    this.context = context;
    this.authService = authService;
    // 获取当前工作区的根路径
    const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
    if (workspaceFolder) {
      this.infoDir = path.join(workspaceFolder.uri.fsPath, '.project-info');
    } else {
      // 如果没有工作区，使用当前目录
      this.infoDir = path.join(process.cwd(), '.project-info');
    }
  }

  /**
   * 获取项目根路径
   */
  private getProjectRoot(): string {
    const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
    if (workspaceFolder) {
      return workspaceFolder.uri.fsPath;
    } else {
      return process.cwd();
    }
  }

  /**
   * 初始化项目信息目录
   */
  private async initializeInfoDirectory(): Promise<void> {
    if (!fs.existsSync(this.infoDir)) {
      fs.mkdirSync(this.infoDir, { recursive: true });
    }
  }

  /**
   * 获取当前Git分支
   */
  private async getCurrentBranch(): Promise<string> {
    try {
      const projectRoot = this.getProjectRoot();
      
      // 首先检查是否是Git仓库
      child_process.execSync('git rev-parse --git-dir', { 
        cwd: projectRoot,
        stdio: 'ignore'
      });
      
      // 如果是Git仓库，获取当前分支
      const result = child_process.execSync('git branch --show-current', { 
        cwd: projectRoot,
        encoding: 'utf-8' 
      });
      return result.trim();
    } catch (error) {
      console.warn('获取Git分支失败，可能不是Git仓库:', error);
      return 'no-git';
    }
  }

  /**
   * 获取Git用户名
   */
  private async getGitUsername(): Promise<string> {
    try {
      const projectRoot = this.getProjectRoot();
      
      // 首先检查是否是Git仓库
      child_process.execSync('git rev-parse --git-dir', { 
        cwd: projectRoot,
        stdio: 'ignore'
      });
      
      // 如果是Git仓库，尝试获取本地配置
      try {
        const result = child_process.execSync('git config user.name', { 
          cwd: projectRoot,
          encoding: 'utf-8' 
        });
        return result.trim();
      } catch (localError) {
        // 如果本地配置失败，尝试获取全局配置
        const result = child_process.execSync('git config --global user.name', { 
          cwd: projectRoot,
          encoding: 'utf-8' 
        });
        return result.trim();
      }
    } catch (error) {
      console.warn('获取Git用户名失败，可能不是Git仓库:', error);
      // 如果不是Git仓库，尝试获取全局Git配置
      try {
        const projectRoot = this.getProjectRoot();
        const result = child_process.execSync('git config --global user.name', { 
          cwd: projectRoot,
          encoding: 'utf-8' 
        });
        return result.trim();
      } catch (globalError) {
        console.warn('获取全局Git用户名失败:', globalError);
        return 'unknown';
      }
    }
  }

  /**
   * 生成基础项目信息（插件可生成的部分）
   */
  public async generateBasicProjectInfo(): Promise<ProjectInfo> {
    const branch = await this.getCurrentBranch();
    const gitUsername = await this.getGitUsername();
    const projectRoot = this.getProjectRoot();
    
    const projectInfo: ProjectInfo = {
      branch,
      timestamp: new Date().toISOString(),
      operator: gitUsername,
      projectName: path.basename(projectRoot),
      workspacePath: projectRoot,
      summary: {}  // 初始化空的summary对象
    };

    return projectInfo;
  }

  /**
   * 保存项目信息到文件
   */
  public async saveProjectInfo(projectInfo: ProjectInfo): Promise<string> {
    await this.initializeInfoDirectory();
    
    // 使用固定的文件名，覆盖更新
    const fileName = 'project-info-current.json';
    const filePath = path.join(this.infoDir, fileName);
    
    fs.writeFileSync(filePath, JSON.stringify(projectInfo, null, 2), 'utf-8');
    
    console.log(`项目信息已更新: ${filePath}`);
    return filePath;
  }

  /**
   * 更新现有项目信息文件（添加摘要内容）
   */
  public async updateProjectInfoWithSummary(filePath: string, summary: any): Promise<void> {
    try {
      if (fs.existsSync(filePath)) {
        const content = fs.readFileSync(filePath, 'utf-8');
        const projectInfo: ProjectInfo = JSON.parse(content);
        
        projectInfo.summary = summary;
        
        fs.writeFileSync(filePath, JSON.stringify(projectInfo, null, 2), 'utf-8');
        console.log(`项目信息已更新: ${filePath}`);
      }
    } catch (error) {
      console.error('更新项目信息失败:', error);
    }
  }

  /**
   * 保存历史版本（可选，用于重要变更时）
   */
  public async saveHistoryVersion(reason: string): Promise<string | null> {
    try {
      const currentFile = await this.getCurrentProjectInfoFile();
      if (!currentFile || !fs.existsSync(currentFile)) {
        return null;
      }

      const content = fs.readFileSync(currentFile, 'utf-8');
      const projectInfo: ProjectInfo = JSON.parse(content);
      
      // 添加保存原因
      const historyInfo = {
        ...projectInfo,
        saveReason: reason,
        savedAt: new Date().toISOString()
      };

      // 生成历史文件名
      const fileName = `project-info-history-${new Date().toISOString().replace(/[:.]/g, '-')}.json`;
      const historyPath = path.join(this.infoDir, fileName);
      
      fs.writeFileSync(historyPath, JSON.stringify(historyInfo, null, 2), 'utf-8');
      console.log(`历史版本已保存: ${historyPath}`);
      
      return historyPath;
    } catch (error) {
      console.error('保存历史版本失败:', error);
      return null;
    }
  }

  /**
   * 获取当前项目信息文件路径
   */
  public async getCurrentProjectInfoFile(): Promise<string | null> {
    try {
      const filePath = path.join(this.infoDir, 'project-info-current.json');
      if (fs.existsSync(filePath)) {
        return filePath;
      }
      return null;
    } catch (error) {
      console.error('获取当前项目信息文件失败:', error);
      return null;
    }
  }

  /**
   * 启动自动更新服务
   */
  public startAutoUpdate(): void {
    // 立即执行一次
    this.generateAndSaveBasicInfo();
    
    // 每30分钟更新一次
    this.updateTimer = setInterval(() => {
      this.generateAndSaveBasicInfo();
    }, 30 * 60 * 1000);
  }

  /**
   * 停止自动更新服务
   */
  public stopAutoUpdate(): void {
    if (this.updateTimer) {
      clearInterval(this.updateTimer);
      this.updateTimer = undefined;
    }
  }

  /**
   * 生成并保存基础项目信息
   */
  private async generateAndSaveBasicInfo(): Promise<void> {
    try {
      // 先获取现有的summary内容
      const existingSummary = await this.getExistingSummary();
      
      const projectInfo = await this.generateBasicProjectInfo();
      
      // 保留现有的summary内容
      if (existingSummary) {
        projectInfo.summary = existingSummary;
      }
      
      await this.saveProjectInfo(projectInfo);
      
      // 通知MCP服务有新文件生成
      this.notifyMCPNewFile();
      
    } catch (error) {
      console.error('生成基础项目信息失败:', error);
    }
  }

  /**
   * 获取现有的summary内容
   */
  private async getExistingSummary(): Promise<any | null> {
    try {
      const currentFile = await this.getCurrentProjectInfoFile();
      if (currentFile && fs.existsSync(currentFile)) {
        const content = fs.readFileSync(currentFile, 'utf-8');
        const existingInfo = JSON.parse(content);
        return existingInfo.summary || null;
      }
    } catch (error) {
      console.warn('获取现有summary失败:', error);
    }
    return null;
  }

  /**
   * 通知MCP服务有新文件生成
   */
  private notifyMCPNewFile(): void {
    // 这里可以通过事件或其他方式通知MCP服务
    // 暂时使用console.log，后续可以集成具体的MCP通信机制
    console.log('新的项目信息文件已生成，MCP服务可以开始处理');
  }

  /**
   * 检测分支变化并重新生成信息
   */
  public async checkBranchChange(): Promise<void> {
    const currentBranch = await this.getCurrentBranch();
    const lastBranch = this.context.globalState.get('lastBranch', '');
    
    if (currentBranch !== lastBranch && lastBranch !== '') {
      console.log(`分支从 ${lastBranch} 切换到 ${currentBranch}`);
      
      // 保存历史版本
      await this.saveHistoryVersion(`分支切换: ${lastBranch} -> ${currentBranch}`);
      
      await this.context.globalState.update('lastBranch', currentBranch);
      await this.generateAndSaveBasicInfo();
    } else if (lastBranch === '') {
      // 首次设置分支
      await this.context.globalState.update('lastBranch', currentBranch);
    }
  }
} 